<?php

namespace App\Http\Controllers\Innerend;


use App\Models\User;
use App\Models\SiteType;
use App\Models\TopicSubscribe;
use App\Models\UserGold;
use App\Models\UserModify;
use App\Models\UserShouting;
use App\Models\UserVerify;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class UserController extends BaseController
{
    protected $list_cache = true;

    // 成员管理
    public function initialize()
    {
        parent::initialize();

        $this->model = 'user';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        // 身份认证类型
        $typeDb   = new SiteType();
        $typeList = $typeDb->isCache(true)->getAll(['channel' => 'user_type']);
        $types    = array_column($typeList, 'name', 'id');
        $verifys  = [0 => '待审核', 1 => '审核通过', 2 => '审核不通过'];

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_id      = $item['id'];
            $status   = $item['status'] == 1 ? '正常' : '禁用';
            $statusOp = $item['status'] == 1 ? '禁用' : '启用';
            // 操作
            $operate = $listHtml->operate_list(['uid' => $_id], '金币详情', '/user-gold/lists');
            $operate .= $listHtml->operate_status(['id' => $_id, 'status' => 1 - $item['status']], $statusOp, $item['status']);
            $operate .= $listHtml->operate_edit(['id' => $_id], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该用户吗？');

            // 图片
            $verify     = $verifys[$item['verify']];
            $apply_type = $types[$item['apply_type']] ?? '-';
            $imageHtml  = '';
            if($item['head_img']){
                $image     = $this->showQiniuImage($this->getHeadImg($item['head_img']), 100, 100);
                $imageHtml = "<img src='".$image."' style='width:100px;' >";
            }

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($item['username']);
            $tr .= $listHtml->list_td($item['realname']);
            $tr .= $listHtml->list_td($imageHtml);
            $tr .= $listHtml->list_td($item['mobile']);
            $tr .= $listHtml->list_td($status);
            $tr .= $listHtml->list_td($item['is_apply'] == 1 ? '是' : '否');
            $tr .= $listHtml->list_td($verify);
            //$tr .= $listHtml->list_td($apply_type);
            $tr .= $listHtml->list_td($item['city']);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        return [
            'username' => ['用户名', 120],
            'realname' => ['真实姓名', 120],
            'head_img' => '头像',
            'mobile'   => '手机号',
            'status'   => ['状态', 40],
            'is_apply' => ['是否申请认证', 40],
            'verify'   => ['认证审核', 40],
            'city'     => ['城市', 60],
            'ctime'    => ['创建时间', 120],
            'operate'  => ['操作', 250],
        ];
    }


    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        $username = $form->formInput('username', $info['username'] ?? '', '用户名');
        $username = $form->formShow($info['username'] ?? '');
        $head_img = $form->formImage('head_img', $info['head_img'] ?? '');
        $head_img = $form->formImage('head_img', $this->getHeadImg($info['head_img']??''));
        $mobile   = $form->formInput('mobile', $info['mobile'] ?? '', '手机号');
        $city     = $form->formInput('city', $info['city'] ?? '');
        $_id      = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('用户名', $username);
        $html .= $form->makeItem('头像', $head_img);
        $html .= $form->makeItem('手机号', $mobile);
        $html .= $form->makeItem('城市', $city);
        $html .= $_id;

        return $html;
    }

    // 启用禁用
    public function status()
    {
        $_value = $this->getData('status', 0, 'intval');
        $this->throwIf(is_null($_value), '是否启用状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否启用状态必须为0或1！');

        $id   = $this->id;
        $data = ['status' => $_value, 'uid' => $id];
        // 执行
        $deal   = $this->checkModel($this->model);
        $result = $deal->oneEdit(['id' => $id], $data);
        $this->throwIf($result === false, $deal->getError());

        return $this->success([], '更新成功！');
    }

    // 设置可以后台编辑文章的用户
    public function toEdit()
    {
        $_value = $this->getData('value', 0, 'intval');
        $this->throwIf(is_null($_value), '是否编辑状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否编辑状态必须为0或1！');

        $id   = $this->id;
        $data = ['is_edit' => $_value, 'uid' => $id];
        // 执行
        $deal   = $this->checkModel($this->model);
        $result = $deal->oneEdit(['id' => $id], $data);
        $this->throwIf($result === false, $deal->getError());

        return $this->success([], '更新成功！');
    }

    // 订阅话题列表
    public function subscribe()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new TopicSubscribe();
        $result = $model->getTopic(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 订阅话题列表
    public function follow()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new UserShouting();
        $result = $model->getFollow(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 粉丝
    public function fans()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new UserShouting();
        $result = $model->getFans(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 修改密码
    public function password()
    {
        $password = $this->getData('password', '123456', 'trim');

        $data  = ['password' => $password, 'uid' => $this->id,];
        $where = ['id' => $this->id];

        $model = new User();
        $data  = $model->checkData($data, ['id' => $this->id,]);
        $this->throwIf($data === false, $model->getError());

        $result = $model->oneEdit($where, $data);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 添加操作深蓝币
    public function gold()
    {
        $uid   = $this->id;
        $gold  = $this->getData('gold', 0, 'intval');
        $title = $this->getData('reason', null, 'trim');
        $this->throwReturn(empty($uid), '请指定要操作的用户！');
        $this->throwReturn(empty($gold), '请填写要操作的变化金额！');
        $this->throwReturn(empty($title), '请填写操作原因！');
        $this->throwReturn(mb_strlen($title) >= 20, '操作原因不能操作20个字符！');

        // 判断用户金币数量
        $goldDb = new UserGold();
        $modDb  = new UserModify();
        $userDb = new User();
        // 用户信息
        $user   = $userDb->isCache(true)->oneFind(['id' => $uid]);
        $afGold = $user['gold'] + $gold;
        $this->throwReturn($afGold < 0, '用户金币不足！');
        // 用户附件信息 用于删除缓存
        $moInfo = $modDb->isCache(true)->oneFind(['uid' => $uid]);

        // 整理数据
        $data = ['uid' => $uid, 'date' => date('Ymd'), 'title' => $title, 'field' => '', 'price' => $gold,];

        // 保存数据
        $goldDb->fill($data);
        DB::beginTransaction();
        try{
            // 增加用户金币
            $modDb->where('uid', $uid)->update(['gold' => $afGold]);
            // 增加金币记录
            $goldDb->save();
            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 删除缓存
        $goldDb->deleteCacheShow($data);
        $userDb->deleteCacheShow($user);
        $modDb->deleteCacheShow($moInfo);

        return $this->success([], '用户金币操作成功！');
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['status' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表搜索
    protected function listWhere()
    {
        $where    = [['status', '>=', 0]];
        $is_edit  = $this->getData('is_edit', null, 'intval');
        $is_virtu = $this->getData('is_virtual', null, 'intval');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $from_uid = $this->getData('from_uid', 0, 'intval');
        $mobile   = $this->getData('mobile', null, 'trim');
        $keyword  = $this->getData('keyword', null, 'trim');
        if($keyword){
            $this->list_cache = false;
            //$where[] = $this->orWhere('email|nickname|username|position|realname', 'like', $keyword);
            $where[] = $this->orWhere('username', 'like', "%$keyword%");
        }
        if($mobile){
            $where[] = $this->orWhere('mobile', 'like', "%$mobile%");
            // 不在缓存
            $this->list_cache = false;
        }
        if($from_uid){
            $where[] = $this->orWhere('from_uid', '=', $from_uid);
            // 不在缓存
            $this->list_cache = false;
        }
        if(!is_null($is_virtu)){
            $where[] = ['is_virtual', '=', $is_virtu];
        }
        if(!is_null($is_edit)){
            $where[] = ['is_edit', '=', $is_edit];
        }
        if($is_apply){
            $where[] = ['is_apply', '=', 1];
            $where[] = ['verify', '=', 1];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $mobile   = $this->getData('mobile', '', 'trim');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $links    = $this->getData('links', [], 'is_array');
        $files    = $this->getData('files', [], 'is_array');
        $areas    = $this->getData('areas', [], 'is_array');
        $this->throwIf(empty($mobile), '请填写手机号码！');
        $isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        $this->throwIf(!$isMobile, '请填写正确手机号!!');
        if($is_apply){
            $this->throwIf(count($files) != count($files, 1), '请传递正确文件地址！');
            $this->throwIf(count($links) != count($links, 1), '请传递正确网络连接！');
            $this->throwIf(count($areas) != count($areas, 1), '请传递正确网络擅长领域！');
        }

        // 检查手机号是否存在
        $userDb  = new User();
        $yzwhere = [['mobile', '=', $mobile], ['status', '<>', -1]];
        $info    = $userDb->where($yzwhere)->first();
        $this->throwIf($info, '该手机号已经存在！');

        // 组合
        $data = [
            // 'from_uid'     => $this->getData("from_uid"),
            // 'id'           => $this->getData("id"),
            // 'score'        => $this->getData("score"),
            // 'password'     => $this->getData("password"),
            // 'itype'        => $this->getData("itype"),
            // 'channel'      => $this->getData("channel"),
            // 'uid'          => $this->getData("uid"),
            // 'gold'         => $this->getData("gold"),
            // 'last_ip'      => $this->getData("last_ip"),
            // 'last_time'    => $this->getData("last_time"),
            // 'sign'         => $this->getData("sign"),
            // 'phone'        => $this->getData("phone"),

            // 使用
            //'email'        => $this->getData('email', null, 'trim'),
            //'nickname'     => $this->getData("nickname", null, 'trim'),
            //'is_recommend' => $this->getData("is_recommend", 0, 'intval'),
            //'is_index'     => $this->getData("is_index", 0, 'intval'),
            'username'    => $this->getData('username', null, 'trim'),
            'mobile'      => $mobile,
            'head_img'    => $this->getData('head_img', '', 'trim'),
            'sex'         => $this->getData('sex', '0', 'trim'),
            'is_virtual'  => $this->getData("is_virtual", 0, 'intval'),
            'is_edit'     => $this->getData("is_edit", 0, 'intval'),
            'status'      => $this->getData('status', 1, 'intval'),

            // 认证
            'is_apply'    => $is_apply,
            'verify'      => $is_apply == 1 ? 1 : 0,
            'realname'    => $this->getData('realname', '', 'trim'),
            'apply_type'  => $this->getData('apply_type', 0, 'intval'),
            'position'    => $this->getData('position', '', 'trim'),
            'areas'       => $this->jsonChinese($areas),
            'description' => $this->getData('description', '', 'trim'),
            'files'       => $this->jsonChinese($files),
            'links'       => $this->jsonChinese($links),

            'city'        => $this->getData("city", '', 'trim'),
            // 关联联系方式的字段
            // 'wechat'       => $this->getData("wechat"),
            // 'qq'           => $this->getData("qq"),
            // 'sina'         => $this->getData("sina"),
            // 'apple'        => $this->getData("apple"),

            // 认证操作的字段
            // 'is_apply'    => $this->getData("is_apply"),
            // 'apply_type'  => $this->getData("apply_type"),
            // 'verify'      => $this->getData("verify"),
            // 'address'     => $this->getData("address"),
            // 'position'    => $this->getData("position"),
            // 'files'       => $this->getData("files"),
            // 'links'       => $this->getData("links"),
            // 'areas'       => $this->getData("areas"),
            // 'description' => $this->getData("description"),

            // 'is_auth'    => $this->getData("is_auth"),
            // 'follow_no'  => $this->getData("follow_no"),
            // 'shy_no'     => $this->getData("shy_no"),
            // 'topic_no'   => $this->getData("topic_no"),
            // 'collect_no' => $this->getData("collect_no"),
            // 'comment_no' => $this->getData("comment_no"),
            // 'praise_no'  => $this->getData("praise_no"),
            // 'view_no'    => $this->getData("view_no"),
            // 'invite_no'  => $this->getData("invite_no"),
            // 'fresh_no'   => $this->getData("fresh_no"),
            // 'publish_no' => $this->getData("publish_no"),
            // 'shy_no'     => $this->getData("shy_no"),

            // 'home'             => $this->getData("home"),
            // 'business'         => $this->getData("business"),
            // 'business_summary' => $this->getData("business_summary"),
            // 'company'          => $this->getData("company"),
            // 'department'       => $this->getData("department"),
            // 'certify_type'     => $this->getData("certify_type"),
            // 'certify_code'     => $this->getData("certify_code"),
            // 'invite_code'      => $this->getData("invite_code"),

            // 'dtTime'      => $this->getData("dtTime"),
            // 'dtLast'      => $this->getData("dtLast"),
            // 'idBangDing'  => $this->getData("idBangDing"),
            // 'mediaID'     => $this->getData("mediaID"),
            // 'mediaUserID' => $this->getData("mediaUserID"),
            // 'sIdCard'     => $this->getData("sIdCard"),
            // 'sCard'       => $this->getData("sCard"),
            // 'sCreditCode' => $this->getData("sCreditCode"),
            // 'sLicense'    => $this->getData("sLicense"),
            // 'sLegalName'  => $this->getData("sLegalName"),
            // 'sLegalPhone' => $this->getData("sLegalPhone"),
            // 'sAuthorize'  => $this->getData("sAuthorize"),
            // 'sCheckIn'    => $this->getData("sCheckIn"),
        ];

        // 检查用户名
        if(empty($data['username'])){
            $data['username'] = 'SLH'.$userDb->getAutoInc();
        }

        // 检查唯一性
        //$data = $userDb->checkUser($data);  // 用户名是否重复
        //$this->throwIf($data === false, $userDb->getError());

        // 检查验证 如果是认证用户
        if($is_apply){
            // 验证信息
            $rules  = ["apply_type" => 'required|gt:0', "realname" => 'required', "position" => 'required', "areas" => 'required', "files" => 'required',];
            $msg    = ["apply_type" => '身份类型', "realname" => '真实姓名', "position" => '头衔', "areas" => '擅长领域', "description" => '描述', "files" => '证明文件',];
            $result = $userDb->validator($data, $rules, $msg);
            $this->throwReturn($result === false, $userDb->getError());
            $this->throwReturn($data['areas'] == '[]', '请选择擅长的领域！');
            $this->throwReturn($data['files'] == '[]', '请上传证明文件！');
        }

        // 审核内容
        $this->baiduTextCensor($data);


        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        // 参数
        $mobile   = $this->getData('mobile', '', 'trim');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $links    = $this->getData('links', [], 'is_array');
        $files    = $this->getData('files', [], 'is_array');
        $areas    = $this->getData('areas', [], 'is_array');
        $this->throwIf(empty($mobile), '请填写手机号码！');
        $isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        $this->throwIf(!$isMobile, '请填写正确手机号!!');
        if($is_apply){
            $this->throwIf(count($files) != count($files, 1), '请传递正确文件地址！');
            $this->throwIf(count($links) != count($links, 1), '请传递正确网络连接！');
            $this->throwIf(count($areas) != count($areas, 1), '请传递正确网络擅长领域！');
        }

        // 检查手机号是否存在
        $userDb  = new User();
        $yzwhere = [['mobile', '=', $mobile], ['status', '<>', -1], ['id', '<>', $this->id]];
        $info    = $userDb->where($yzwhere)->first();
        $this->throwIf($info, '该手机号已经存在！');

        // 组合
        $data = [
            // 使用
            //'email'        => $this->getData('email', null, 'trim'),
            //'nickname'     => $this->getData("nickname", null, 'trim'),
            //'is_recommend' => $this->getData("is_recommend", 0, 'intval'),
            //'is_index'     => $this->getData("is_index", 0, 'intval'),
            'username'    => $this->getData('username', null, 'trim'),
            'mobile'      => $mobile,
            'head_img'    => $this->getData('head_img', '', 'trim'),
            'sex'         => $this->getData('sex', '0', 'trim'),
            'is_virtual'  => $this->getData("is_virtual", 0, 'intval'),
            'is_edit'     => $this->getData("is_edit", 0, 'intval'),
            //'status'      => $this->getData('status', 1, 'intval'),
            'city'        => $this->getData("city", '', 'trim'),

            // 认证
            'is_apply'    => $is_apply,
            'verify'      => $is_apply == 1 ? 1 : 0,
            'realname'    => $this->getData('realname', null, 'trim'),
            'apply_type'  => $this->getData('apply_type', 0, 'intval'),
            'position'    => $this->getData('position', null, 'trim'),
            'areas'       => $this->jsonChinese($areas),
            'description' => $this->getData('description', '', 'trim'),
            'files'       => $this->jsonChinese($files),
            'links'       => $this->jsonChinese($links),
        ];

        // 检查唯一性
        //$model = new User();
        //$data  = $model->checkUser($data, $this->id);

        // 检查验证 如果是认证用户
        if($is_apply){
            // 验证信息
            $rules  = ["apply_type" => 'required|gt:0', "realname" => 'required', "position" => 'required', "areas" => 'required', "files" => 'required',];
            $msg    = ["apply_type" => '身份类型', "realname" => '真实姓名', "position" => '头衔', "areas" => '擅长领域', "description" => '描述', "files" => '证明文件',];
            $result = $userDb->validator($data, $rules, $msg);
            $this->throwReturn($result === false, $userDb->getError());
            $this->throwReturn($data['areas'] == '[]', '请选择擅长的领域！');
            $this->throwReturn($data['files'] == '[]', '请上传证明文件！');
        }

        // 审核内容
        $this->baiduTextCensor($data);

        return $data;
    }

}


